package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    private final String CART_PREFIX = "gulimall:cart";


    /**
     * 将商品添加到购物车
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get("" + skuId);

        //购物车无此商品
        if(StringUtils.isEmpty(res)){


            CartItem cartItem = new CartItem();
            //2.商品添加到购物车

            //远程查询sku
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {

                //远程查询要添加的商品的信息

                R skuInfo = productFeignService.getSkuInfo(skuId);

                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                cartItem.setCount(num);
                cartItem.setCheck(true);
                cartItem.setImage(data.getSkuDesc());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
                cartItem.setSkuId(skuId );
            },threadPoolExecutor);

            //远程查询sku的组合信息
            CompletableFuture<Void>  getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {


                List<String> values = productFeignService.getSkuSaleAttrValue(skuId);

                cartItem.setSkuAttr(values);
            }, threadPoolExecutor);

            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();

            String s = JSON.toJSONString(cartItem);

            System.out.println("解析后的值："+s);
            cartOps.put(skuId.toString(),s);

            return cartItem;

        }
        else {
            CartItem cartItem = new CartItem();
            //购物车有此商品，修改数量即可
           cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    /**
     * 获取购物车某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String str = (String) cartOps.get(skuId.toString());

        CartItem item = JSON.parseObject(str, CartItem.class);

        return item;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {

        Cart cart = new Cart();

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        //用户已经登录
        if(userInfoTo.getUserId()!=null){

            String cartKey =  CART_PREFIX+userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);



            //获取临时用户购物车数据
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);

            //2、如果临时购物车的数据还没合并
            if(tempCartItems!=null){
                //临时购物车有数据，需要合并
                for (CartItem item : tempCartItems) {

                     addToCart(item.getSkuId(), item.getCount());


                }
                clearCart(tempCartKey);
            }

            //再来获取登录购物车数据,包含临时购物车数据和登录后购物车数据
            List<CartItem> cartItems = getCartItems(cartKey);

            cart.setItems(cartItems);

        }else{

            //用户没登录
            //获取临时购物车所有数据

            String cartKey =  CART_PREFIX+userInfoTo.getUserKey();

            List<CartItem> cartItems = getCartItems(cartKey);

            cart.setItems(cartItems);

        }




        return cart;
    }

    @Override
    public void clearCart(String cartKey) {

        redisTemplate.delete(cartKey);


    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        CartItem cartItem = getCartItem(skuId);

        cartItem.setCheck(check==1?true:false);

        String s = JSON.toJSONString(cartItem);

        cartOps.put(skuId.toString(),s);


    }

    //修改购物数量
    @Override
    public void changetItemCount(Long skuId, Integer num) {

        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));


    }

    //删除购物项
    @Override
    public void deleteItem(Long skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        cartOps.delete(skuId.toString());


    }

    @Override
    public List<CartItem> getUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        if(userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);

            //获取被选中的购物项
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck()).collect(Collectors.toList());

            List<CartItem> collect1 = collect.stream().map(item -> {
                BigDecimal price = productFeignService.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());

            return collect1;

        }

    }


    //获取到操作的购物车
    private BoundHashOperations<String,Object,Object> getCartOps() {

        String cartKey = "";
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        if(userInfoTo.getUserId()!=null){

            cartKey = CART_PREFIX + userInfoTo.getUserId();

        }else {

            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }

    private  List<CartItem> getCartItems(String cartKey){

        //2、没登录
         BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();

        if(values!=null&&values.size()>0){
            List<CartItem> collect = values.stream().map(obj -> {

                String str = (String) obj;
                CartItem cartItem = JSONObject.parseObject(str, CartItem.class);
                return  cartItem;
            }).collect(Collectors.toList());


            return collect;
        }
        return null;

    }


}
